/** 
* <p>Title: AssignPrivilegeHandler.java</p> 
* <p>Description: </p> 
* <p>Copyright: Copyright (c) 2012</p> 
* <p>Company: hnii</p> 
* @author LiuC
* @date 2012-9-10 
* @version 1.0 
*/ 
package com.powerManager.sdk.handlers;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.jdbc.core.JdbcTemplate;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.powerManager.sdk.common.InitSystem;
import com.powerManager.sdk.common.JdbcSingleton;
import com.powerManager.sdk.common.PagingResult;
import com.powerManager.sdk.entity.MenuButtonEntity;
import com.powerManager.sdk.utils.JsonUtil;

/** 
 * <p>Title: AssignPrivilegeHandler</p> 
 * <p>Description: 用于权限分配，解决角色权限分配和用户权限分配冲突</p> 
 * <p>Company: hnii</p> 
 * @author    LiuC
 * @date      2012-9-10 
 */
public class AssignPrivilegeHandler {
	
	/** -- 用户模块,用户列表
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String loadUserJSON(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sql="SELECT user_id as UserId,login_name,password,department_id,nickname,status,password_status,remark FROM sys_user";
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		PagingResult pr = new PagingResult(sql);
		String json = null;
		try {
			json = pr.pagingToJson(Integer.parseInt(pageSize), Integer.parseInt(page));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(json);
		return "text:"+json;
	}
	
	/** 
	* <p>Title: getRolePrivilege</p> 
	* <p>Description: 根据用户ID获取用户权限</p> 
	* @param request
	* @param response
	* @return 
	*/ 
	public String getUserPrivilege(HttpServletRequest request, HttpServletResponse response){
		// 用户Id
		String userId = "";
		StringBuffer json = new StringBuffer("{\"Data\":");
		userId = request.getParameter("UserId");
		if (null != userId && userId.length() > 0) {
			StringBuffer sql = new StringBuffer(
					"select case when sys.PrivilegeAccess='Sys_Menu' then sys.PrivilegeAccessKey else '0'  END as MenuID, "
							+ "case when sys.PrivilegeAccess='Sys_Button' then sys.PrivilegeAccessKey else '0'  END as BtnID, "
							+" case when sys.PrivilegeOperation='Permit' then true else false end as Permit,"
							+" case when sys.PrivilegeOperation='Forbid' then true else false end as Forbid"+
							" from sys_privilege sys"+
							" where 1=1 and sys.PrivilegeMaster='CF_User' ");
			sql.append(" and sys.PrivilegeMasterKey='").append(userId).append("'");
			System.out.println("查询用户权限的sql"+sql.toString());
			JdbcTemplate jdbc = JdbcSingleton.getJdbcTemplate();
			List<Map<String, Object>> rows = jdbc.queryForList(sql.toString());
			json.append(JsonUtil.toJson(rows));
			json.append("}");
		}
		System.out.println("权限"+json.toString());
		return "text:"+json.toString();
	}
	
	
	/** 
	* <p>Title: addUserPrivilege</p> 
	* <p>Description:根用户Id，新增用户权限 </p> 
	* @param request
	* @param response
	* @return 
	*/ 
	@SuppressWarnings("static-access")
	public String addUserPrivilege(HttpServletRequest request, HttpServletResponse response){
		JdbcSingleton jdbc = new JdbcSingleton();
		//获取用户Id
		String userId = request.getParameter("UserId");
		//获取权限
		//获取权限角色json对象
		String rolePrivilege = request.getParameter("DataJSON");
		System.out.println("权限集合："+rolePrivilege);
		//获取权限集合list
		List<MenuButtonEntity> listPrivilege = getPrivilegeToList(rolePrivilege);
		String PrivilegeAccessKey = "";
		String Permit = "";
		String  Forbid = "";
		String  PrivilegeOperation = "";
		String PrivilegeAccess = "";
		int i = 0;
		int result = 0;
		String sql = "";
		if (deletePrivilege(userId,"CF_User")) {
			StringBuffer bf = new StringBuffer(
					"insert into sys_privilege(PrivilegeMaster,PrivilegeMasterKey,PrivilegeAccess,PrivilegeAccessKey,PrivilegeOperation)  values");
			for (MenuButtonEntity menuButtonEntity : listPrivilege) {
				PrivilegeAccessKey = menuButtonEntity.getMenuID().equals("0")?menuButtonEntity.getBtnID():menuButtonEntity.getMenuID();
				PrivilegeAccess = menuButtonEntity.getMenuID().equals("0")?"Sys_Button":"Sys_Menu";
				PrivilegeOperation = menuButtonEntity.getPermit().equals("true")?"Permit":"Forbid";
				
				Permit = menuButtonEntity.getPermit();
				Forbid = menuButtonEntity.getForbid();
				if(Permit.equals("true") || Forbid.equals("true")){
					//bf.append("(GET_SEQ('SEQ_PRIVILEGE','0')").append("'CF_Role',");
					bf.append("('CF_User',");
					bf.append("'").append(userId).append("',");
					bf.append("'").append(PrivilegeAccess).append("',");
					bf.append("'").append(PrivilegeAccessKey).append("',");
					bf.append("'").append(PrivilegeOperation).append("'),");
					i = i+1;
				}
			}
			if(bf.toString().endsWith(",")){
				sql = bf.toString().substring(0, bf.length()-1);
			}
			result = jdbc.getJdbcTemplate().update(sql);
		}
		InitSystem.loadPrivilege();
		return result >0?"text:true":"text:false";
	}
	
	
	
	/** 
	* <p>Title: getRolePrivilege</p> 
	* <p>Description: 根据角色ID获取角色权限</p> 
	* @param request
	* @param response
	* @return 
	*/ 
	public String getRolePrivilege(HttpServletRequest request, HttpServletResponse response){
		// 角色Id
		String roleId = "";
		StringBuffer json = new StringBuffer("{\"Data\":");
		roleId = request.getParameter("RoleId");
		if (null != roleId && roleId.length() > 0) {
			StringBuffer sql = new StringBuffer(
					"select case when sys.PrivilegeAccess='Sys_Menu' then sys.PrivilegeAccessKey else '0'  END as MenuID, "
							+ "case when sys.PrivilegeAccess='Sys_Button' then sys.PrivilegeAccessKey else '0'  END as BtnID "+
							" from sys_privilege sys"+
							" where 1=1 and sys.PrivilegeMaster='CF_Role'");
			sql.append(" and sys.PrivilegeMasterKey='").append(roleId).append("'");
			System.out.println("查询角色权限的sql"+sql.toString());
			JdbcTemplate jdbc = JdbcSingleton.getJdbcTemplate();
			List<Map<String, Object>> rows = jdbc.queryForList(sql.toString());
			json.append(JsonUtil.toJson(rows));
			json.append("}");
		}
		return "text:"+json.toString();
	}
	
	
	/** 
	* <p>Title: addRolePrivilege</p> 
	* <p>Description:根据角色Id，新增角色权限 </p> 
	* @param request
	* @param response
	* @return 
	*/ 
	@SuppressWarnings("static-access")
	public String addRolePrivilege(HttpServletRequest request, HttpServletResponse response){
		JdbcSingleton jdbc = new JdbcSingleton();
		//获取角色Id
		String roleId = request.getParameter("RoleId");
		//获取权限
		//获取权限角色json对象
		String rolePrivilege = request.getParameter("DataJSON");
		System.out.println("权限集合："+rolePrivilege);
		//获取权限集合list
		List<MenuButtonEntity> listPrivilege = getPrivilegeToList(rolePrivilege);
		String PrivilegeAccessKey = "";
		String Permit = "";
		String  Forbid = "";
		String  PrivilegeOperation = "";
		String PrivilegeAccess = "";
		int i = 0;
		int result = 0;
		String sql = "";
		if (deletePrivilege(roleId,"CF_Role") && listPrivilege.size()>0) {
			StringBuffer bf = new StringBuffer(
					"insert into sys_privilege(PrivilegeMaster,PrivilegeMasterKey,PrivilegeAccess,PrivilegeAccessKey,PrivilegeOperation)  values");
			for (MenuButtonEntity menuButtonEntity : listPrivilege) {
				PrivilegeAccessKey = menuButtonEntity.getMenuID().equals("0")?menuButtonEntity.getBtnID():menuButtonEntity.getMenuID();
				PrivilegeAccess = menuButtonEntity.getMenuID().equals("0")?"Sys_Button":"Sys_Menu";
				PrivilegeOperation = "Permit";
				
				Permit = menuButtonEntity.getPermit();
				Forbid = menuButtonEntity.getForbid();
				if(Permit.equals("true") || Forbid.equals("true")){
					//bf.append("(GET_SEQ('SEQ_PRIVILEGE','0')").append("'CF_Role',");
					bf.append("('CF_Role',");
					bf.append("'").append(roleId).append("',");
					bf.append("'").append(PrivilegeAccess).append("',");
					bf.append("'").append(PrivilegeAccessKey).append("',");
					bf.append("'").append(PrivilegeOperation).append("'),");
					i = i+1;
				}
			}
			if(bf.toString().endsWith(",")){
				sql = bf.toString().substring(0, bf.length()-1);
			}
			result = jdbc.getJdbcTemplate().update(sql);
		}
		InitSystem.loadPrivilege();
		return result >0?"text:true":"text:false";
	}
	


	/** 
	* <p>Title: getAllMenuButton</p> 
	* <p>Description:获取所有的菜单按钮权限 </p> 
	* @param request
	* @param response
	* @return
	* @throws Exception 
	*/ 
	public String getAllMenuButton(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String sql="select MenuID,MenuNo,MenuParentNo,MenuName,MenuIcon,BtnID from V_AllMenuAndButton";
		PagingResult pr = new PagingResult(sql);
		String json = null;
		try {
			json = pr.treeToJson(sql, null, "MenuNo", "MenuParentNo", "0");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "text:"+json;
	}
	
	/** 
	* <p>Title: deleteRolePrivilege</p> 
	* <p>Description:</br>
	*删除对象权限 </br>
	*用于给对象分配权限使用</br>
	*这里的对象主要分为角色和用户
	*</p> 
	* @param Id <b>对象ID</b>
	* @return 
	*/ 
	@SuppressWarnings("static-access")
	public boolean deletePrivilege(String Id,String type){
		JdbcSingleton jdbc = new JdbcSingleton();
		String sql = "delete from sys_privilege where PrivilegeMaster=? and  PrivilegeMasterKey=?";
		Object[] params = new Object[]{type,Id};
		int i = 0;
		if(null !=Id && Id.length()>0){
			i = jdbc.getJdbcTemplate().update(sql, params);
		}
		
		return i>=0?true:false;
	}
	
	 /** 
	   * <p>Title: 根据json字符串反悔java List对象</p> 
	   * <p>Description:  根据给定json串解析出内部属性 </p> 
	   * @param jsonStr
	   * @return 
	 */ 
	public static List<MenuButtonEntity>  getPrivilegeToList(String jsonStr){
		Gson gson = new Gson();
	      if(jsonStr ==null || jsonStr.length()<5){  
	           return null;  
	       }  
	      List<MenuButtonEntity> maps = gson.fromJson(jsonStr, new TypeToken<List<MenuButtonEntity>>(){}.getType());
	   return maps;
    }  
	
}
